package servlets.twitterServlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.auth.RequestToken;

public class TwitterLoginCallbackServlet extends HttpServlet {
    private static final long serialVersionUID = 1657390011452788111L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	Long id;
    	Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");        
    	RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken");
        String verifier = request.getParameter("oauth_verifier");
        try {
            twitter.getOAuthAccessToken(requestToken, verifier);
            request.getSession().removeAttribute("requestToken");
            id = twitter.showUser(twitter.getScreenName()).getId();
        } catch (TwitterException e) {
        	request.getSession().removeAttribute("twitter");
            throw new ServletException(e);
        }
        
        //TODO: inserire qui i parametri nella session
        response.sendRedirect(request.getContextPath() + "/SocialNetworkLogin?id=" + id + "&social=Twitter");
    }
}
